package stack

import (
	"algorithm-go/link"
	"errors"
)

// ArrayStack 基于数组实现的线性栈
type ArrayStack struct {
	// count 当前栈中元素数量
	count int
	// dataArray 初始数组容量为16
	dataArray [16]int
}

// push 将元素压入栈,不支持自动扩容
func (stack *ArrayStack) push (element int) (err error) {

	if stack.count >= len(stack.dataArray){
		return errors.New("栈已空")
	}
	// 将元素添加至对应位置
	stack.dataArray[stack.count - 1] = element
	stack.count ++
	return nil
}

// pop 将元素弹出栈
func (stack *ArrayStack) pop() (element int,err error) {

	if stack.count <= 0{
		return 0, errors.New("栈已空")
	}
	stack.count --
	return stack.dataArray[stack.count],nil
}

// LinkedStack 基于链表实现的链式栈
type LinkedStack struct {

	capacity int
	count int
	head *link.Node
}

// push 数据压入栈
func (stack *LinkedStack) push(element int) (err error)  {

	if stack.count >= stack.capacity {
		return errors.New("栈已空")
	}
	newNode :=&link.Node{Data: element, Next: stack.head}
	stack.head = newNode
	stack.count ++
	return nil
}

// pop
func (stack *LinkedStack) pop() (element int,err error)  {

	if stack.count <= 0{
		return 0,errors.New("栈已空")
	}
	newHead := stack.head
	stack.head = stack.head.Next
	return newHead.Data, err
}
